package com.lei.dao.impl;

import com.lei.dao.RoleDao;
import com.lei.entity.Role;
import com.lei.util.BaseDb;
import com.lei.util.TransBean;

import java.util.List;
import java.util.Map;

/**
 * @author Lei Chu
 * @Date 2020/10/17 19:43
 */
public class RoleDaoImpl implements RoleDao {

    @Override
    public List<Role> getAllRole() {
        String sql = "select * from t_role where status = 1";
        List<Map> maps = BaseDb.query(sql);
        if (!maps.isEmpty()){
            return TransBean.populate(Role.class,maps);
        }
        return null;
    }

    @Override
    public List<Role> getAllRoleByPage(Role role) {
        StringBuilder sql = new StringBuilder("SELECT\n" +
                "\tt.rid,\n" +
                "\tt.rname,\n" +
                "\tt.memo,\n" +
                "\tt.status,\n" +
                "\tcount \n" +
                "FROM\n" +
                "\tt_role t \n" +
                "\tLEFT JOIN ( SELECT s.roleId, count(*) count FROM t_staff s where s.status=1 GROUP BY s.roleId ) AS rc ON rc.roleId = t.rid where 1=1 ");
        if (role.getRname() != null){
            sql.append(" and rname like '%").append(role.getRname()).append("%' ");
        }
        sql.append(" limit ?,? ");
        List<Map> maps = BaseDb.query(String.valueOf(sql), (role.getPage() - 1) * role.getLimit(), role.getLimit());
        if (maps.size()>0){
            return TransBean.populate(Role.class,maps);
        }
        return null;
    }

    @Override
    public int getCount(Role role) {
        StringBuilder sql = new StringBuilder("select count(*) c from t_role where 1=1 ");
        if (role.getRname() != null){
            sql.append(" and rname like '%").append(role.getRname()).append("%' ");
        }
        List<Map> maps = BaseDb.query(String.valueOf(sql));
        return ((Long)maps.get(0).get("c")).intValue();
    }

    @Override
    public int addRole(Role role) {
        String sql = "insert into t_role (rid,rname,memo,status) values(null,?,?,?)";
        return BaseDb.update(sql,role.getRname(),role.getMemo(),role.getStatus());
    }

    @Override
    public int deleteRole(int rid) {
        String sql = "delete from t_role where rid = ?";
        return BaseDb.update(sql,rid);
    }

    @Override
    public int updateRole(Role role) {
        String sql = "update t_role set rname = ? , memo = ? , status = ? where rid = ?";
        return BaseDb.update(sql,role.getRname(),role.getMemo(),role.getStatus(),role.getRid());
    }

    @Override
    public Integer checkAddName(String rname) {
        String sql = "select rid from t_role where rname = ?";
        List<Map> maps = BaseDb.query(sql, rname);
        if (maps.size()>0){
            // 返回查到的主键
            return (Integer) maps.get(0).get("rid");
        }
        // 查不到就返回 null
        return null;
    }
}
